<?php
namespace app\logic;

use app\facade\Token;
use app\model\post\PostModel;
use app\model\post\TypeModel;
use Exception;

class PostLogic
{
    // 获取 info 信息
    public function getInfo($pid) {
        // info 就是 post 表本身
        $P = PostModel::where("pid",$pid)->find();
        if ($P == null) {
            throw new Exception("文章不存在",1);
        }
        return $P;
    }

    private function getFilepath($pid) {
        return config("file.path.post") . $pid . ".md";
    }

    // 获取文章内容
    public function getContent($pid) {
        $filepath = $this->getFilepath($pid);
        if (!file_exists($filepath)){
            // info 哪里提示不存在一次，这里再来一次，急死用户
            throw new Exception("文章内容获取失败",1);
        }
        return file_get_contents($filepath);
    }

    // 更新数据
    public function updateInfo($pid, $data) {
        $P = PostModel::where("pid",$pid)->find();
        if ($P == null) {
            throw new Exception("文章不存在",1);
        }
        if (!TypeModel::TypeExist($data["type"])) {
            throw new Exception("类型不存在",2);
        }
        $P->save($data);
    }
    // 创建数据
    public function createInfo($data) {
        if (!TypeModel::TypeExist($data["type"])) {
            throw new Exception("类型不存在",2);
        }
        $uid = Token::getUid();
        $data["uid"] = $uid;
        $P = PostModel::create($data);
        return $P["pid"];
    }
    // 更新数据
    public function updateContent($pid, $content) {
        $P = PostModel::where("pid",$pid)->find();
        if ($P == null) {
            throw new Exception("文章不存在",1);
        }
        $filepath = $this->getFilepath($pid);
        file_put_contents($filepath, $content);
    }
    // 创建内容
    public function createContent($pid, $content) {
        $filepath = $this->getFilepath($pid);
        file_put_contents($filepath, $content);
    }
}